package com.zhijian.wharf.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.page.Page;
import com.zhijian.wharf.dao.MqttTopicMapper;
import com.zhijian.wharf.entity.po.MqttTopic;
import com.zhijian.wharf.entity.vo.request.MqttTopicSaveOrUpdateVo;
import com.zhijian.wharf.entity.vo.request.MqttTopicSearchVo;
import com.zhijian.wharf.entity.vo.response.MqttTopicVo;
import com.zhijian.wharf.enums.MqttTopicStatusEnum;
import com.zhijian.wharf.holder.CurrentWebUserHolder;
import com.zhijian.wharf.service.MqttTopicService;
import com.zhijian.wharf.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息主题业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-08-12 19:28:30
 */
@Slf4j
@Service
public class MqttTopicServiceImpl implements MqttTopicService {

    @Autowired
    private MqttTopicMapper mapper;

    @Override
    public MqttTopic selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public MqttTopicVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        check(id);
        mapper.deleteByPrimaryKey(id);
    }

    private void check(Long id) {
        MqttTopic mqttTopic = this.selectById(id);
        AssertUtil.notNull(mqttTopic, "此数据不存在或者已被删除");
        Long createUserId = mqttTopic.getCreateUserId();
        AssertUtil.check(!Objects.equals(createUserId, CurrentWebUserHolder.getUser().getId()), "无权限操作");
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(MqttTopic mqttTopic) {
        Date now = new Date();
        mqttTopic.setCreateTime(now);
        mqttTopic.setUpdateTime(now);
        return mapper.insert(mqttTopic) > 0 ? mqttTopic.getId() : 0L;
    }

    @Override
    public Long insertSelective(MqttTopic mqttTopic) {
        Date now = new Date();
        mqttTopic.setCreateTime(now);
        mqttTopic.setUpdateTime(now);
        return mapper.insertSelective(mqttTopic) > 0 ? mqttTopic.getId() : 0L;
    }

    @Override
    public boolean update(MqttTopic mqttTopic) {
        Date now = new Date();
        mqttTopic.setUpdateTime(now);
        return mapper.updateByPrimaryKey(mqttTopic) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(MqttTopic record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(MqttTopicSaveOrUpdateVo saveOrUpdateVo) {
        Integer count = this.count(MqttTopicSearchVo.builder()
                .topic(saveOrUpdateVo.getTopic())
                .build());
        AssertUtil.check(count > 0, "主题重复");
        MqttTopic mqttTopic = new MqttTopic();
        BeanUtils.copyProperties(saveOrUpdateVo, mqttTopic);
        //默认未发布
        mqttTopic.setStatus(MqttTopicStatusEnum.NORMAL.getCode().byteValue());
        return this.insert(mqttTopic) != 0;
    }

    @Override
    public boolean modify(MqttTopicSaveOrUpdateVo saveOrUpdateVo) {
        MqttTopic old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        Integer count = this.count(MqttTopicSearchVo.builder()
                .notId(saveOrUpdateVo.getId())
                .topic(saveOrUpdateVo.getTopic())
                .build());
        AssertUtil.check(count > 0, "主题重复");
        MqttTopic mqttTopic = new MqttTopic();
        BeanUtils.copyProperties(saveOrUpdateVo, mqttTopic);
        return this.update(mqttTopic);
    }

    @Override
    public MqttTopicVo selectOne(MqttTopicSearchVo mqttTopicSearchVo) {
        return mapper.selectOne(mqttTopicSearchVo);
    }

    @Override
    public Integer count(MqttTopicSearchVo mqttTopicSearchVo) {
        return mapper.count(mqttTopicSearchVo);
    }

    @Override
    public List<MqttTopicVo> selectList(MqttTopicSearchVo mqttTopicSearchVo) {
        return mapper.selectList(mqttTopicSearchVo);
    }

    @Override
    public Page<MqttTopicVo> selectPage(MqttTopicSearchVo mqttTopicSearchVo) {
        AssertUtil.check(Objects.isNull(mqttTopicSearchVo.getPageNum()) || Objects.isNull(mqttTopicSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(mqttTopicSearchVo);
        //分页
        Page<MqttTopicVo> page = new Page<>(true, count, mqttTopicSearchVo.getPageNum(), mqttTopicSearchVo.getPageSize());
        mqttTopicSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<MqttTopicVo> responseVos = this.selectList(mqttTopicSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<MqttTopic> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(MqttTopicSearchVo mqttTopicSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(mqttTopicSearchVo);
    }

    @Override
    public boolean publish(Long id) {
        MqttTopic oldNotice = this.selectById(id);
        AssertUtil.notNull(oldNotice, "此数据不存在或者已被删除");
        AssertUtil.notNull(oldNotice.getStatus() == MqttTopicStatusEnum.CANCEL.getCode().byteValue(), "已发布的主题禁止再次发布");
        return this.updateByPrimaryKeySelective(MqttTopic.builder()
                .id(id)
                .status(MqttTopicStatusEnum.CANCEL.getCode().byteValue())
                .build());
    }

    @Override
    public boolean sub(Long id, Long userId) {
        MqttTopic mqttTopic = this.selectById(id);
        AssertUtil.notNull(mqttTopic, "此数据不存在或者已被删除");
        //订阅用户ID串，以英文逗号隔开
        String subUserIds = mqttTopic.getSubUserIds();
        List<Long> subUserIdList = Lists.newArrayList();
        if (StringUtils.isNotBlank(subUserIds)) {
            subUserIdList = Arrays.stream(subUserIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        }
        subUserIdList.add(userId);
        subUserIds = StrUtil.join(",", subUserIdList);
        return this.updateByPrimaryKeySelective(MqttTopic.builder()
                .id(id)
                .subUserIds(subUserIds)
                .build());
    }

}